import { CallHandler, ExecutionContext, Injectable, NestInterceptor, HttpStatus, BadRequestException } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle()
      .pipe(
        catchError(err => throwError(new BadRequestException(err))),
      )
      .pipe(
        map((s_data = {}) => {
          if (typeof s_data == 'object') {
            let { message = '', ...data } = s_data || {};
            return {
              data,
              message: message || '请求成功',
              code: 200
            }
          } else {
            return s_data;
          }
        })
      );
  }
}
